<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 200px">
          <el-option v-for="dict in genderOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['user:account:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账户ID" align="center" prop="id" width="80" />
      <el-table-column label="用户信息" align="center" min-width="200">
        <template #default="scope">
          <div v-if="scope.row.userBase" class="user-info">
            <el-avatar :size="40" :src="scope.row.userBase.avatar" />
            <div class="user-detail">
              <div class="username">{{ scope.row.userBase.username }}</div>
              <div class="phone">{{ scope.row.userBase.phone || '未设置手机号' }}</div>
            </div>
          </div>
          <el-empty v-else description="暂无用户信息" :image-size="40" />
        </template>
      </el-table-column>
      <el-table-column label="账户余额" align="center" prop="balance" width="120">
        <template #default="scope">
          <div class="balance-wrapper">
            <span class="balance">￥{{ formatBalance(scope.row.balance) }}</span>
            <el-tag v-if="scope.row.balance === 0" size="small" type="info">零余额</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="points" width="100">
        <template #default="scope">
          <div class="points-wrapper">
            <el-tag :type="getPointsType(scope.row.points)" effect="light">
              {{ scope.row.points || '0' }}
            </el-tag>
            <span v-if="scope.row.points === 0" class="points-tip">暂无积分</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" width="100">
        <template #default="scope">
          <el-tag :type="getGenderType(scope.row.gender)" effect="light">
            {{ getGenderLabel(scope.row.gender) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime" width="180">
        <template #default="scope">
          <div class="time-wrapper">
            <span v-if="scope.row.lastLoginTime">{{ parseTime(scope.row.lastLoginTime) }}</span>
            <el-tag v-else size="small" type="info">从未登录</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button v-hasPermi="['user:account:query']" link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button v-hasPermi="['user:account:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['user:account:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改用户账户对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="accountRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="请选择用户"
            :disabled="!!form.id"
            filterable
            remote
            :remote-method="handleUserSearch"
            :loading="userLoading"
            style="width: 100%"
          >
            <el-option v-for="item in userOptions" :key="item.id" :label="item.username" :value="item.id">
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.username }}</span>
                <span style="color: #999; font-size: 13px">{{ item.phone }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户余额" prop="balance">
          <el-input-number v-model="form.balance" :precision="2" :step="0.1" :min="0" placeholder="请输入账户余额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="form.points" :min="0" placeholder="请输入积分" style="width: 100%" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户账户详情对话框 -->
    <el-dialog v-model="viewOpen" title="用户账户详情" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="账户ID">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="用户信息">
          <div v-if="viewForm.userBase" class="user-info-detail">
            <el-avatar :size="60" :src="viewForm.userBase.avatar" />
            <div class="user-detail">
              <div class="username">{{ viewForm.userBase.username }}</div>
              <div class="phone">{{ viewForm.userBase.phone || '未设置手机号' }}</div>
              <div class="email">{{ viewForm.userBase.email || '未设置邮箱' }}</div>
            </div>
          </div>
          <el-empty v-else description="暂无用户信息" :image-size="40" />
        </el-descriptions-item>
        <el-descriptions-item label="账户余额">
          <div class="balance-wrapper">
            <span class="balance">￥{{ formatBalance(viewForm.balance) }}</span>
            <el-tag v-if="viewForm.balance === 0" size="small" type="info">零余额</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="积分">
          <div class="points-wrapper">
            <el-tag :type="getPointsType(viewForm.points)" effect="light" size="large">
              {{ viewForm.points || '0' }}
            </el-tag>
            <span v-if="viewForm.points === 0" class="points-tip">暂无积分</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag :type="getGenderType(viewForm.gender)" effect="light" size="large">
            {{ getGenderLabel(viewForm.gender) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最后登录时间">
          <div class="time-wrapper">
            <span v-if="viewForm.lastLoginTime">{{ parseTime(viewForm.lastLoginTime) }}</span>
            <el-tag v-else size="small" type="info">从未登录</el-tag>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="UserAccount">
import { ref, getCurrentInstance, onMounted } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { listUserAccount, getUserAccount, addUserAccount, updateUserAccount, delUserAccount } from '@/api/user/account';
import { UserAccountQuery, UserAccountVo, UserAccountForm } from '@/api/user/account/types';
import { parseTime } from '@/utils/ruoyi';
import type { FormInstance, FormRules } from 'element-plus';
import { listUser } from '@/api/user/user';
import type { UserVo } from '@/api/user/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const accountList = ref<UserAccountVo[]>([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const viewOpen = ref(false);
const viewForm = ref<UserAccountVo>({} as UserAccountVo);

// 表单ref
const accountRef = ref<FormInstance>();
const queryRef = ref<FormInstance>();

// 性别选项
const genderOptions = ref([
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]);

// 查询参数
const queryParams = ref<UserAccountQuery>({
  pageNum: 1,
  pageSize: 10,
  userId: undefined,
  gender: undefined
});

// 表单参数
const form = ref<UserAccountForm>({
  id: undefined,
  userId: undefined,
  balance: 0,
  points: 0,
  gender: 0
});

// 表单校验
const rules = ref<FormRules>({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  balance: [{ required: true, message: '账户余额不能为空', trigger: 'blur' }],
  points: [{ required: true, message: '积分不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '性别不能为空', trigger: 'change' }]
});

// 用户选项
const userOptions = ref<UserVo[]>([]);
const userLoading = ref(false);

/** 格式化余额显示 */
function formatBalance(balance?: number | string | null) {
  if (balance === undefined || balance === null) {
    return '0.00';
  }
  const num = Number(balance);
  return isNaN(num) ? '0.00' : num.toFixed(2);
}

/** 查询用户账户列表 */
function getList() {
  loading.value = true;
  listUserAccount(queryParams.value).then((response) => {
    accountList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    userId: undefined,
    balance: 0,
    points: 0,
    gender: 0
  };
  accountRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: UserAccountVo[]) {
  ids.value = selection.map((item) => item.id!);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 用户搜索 */
function handleUserSearch(query: string) {
  if (query) {
    userLoading.value = true;
    listUser({
      pageNum: 1,
      pageSize: 10,
      username: query
    }).then((response) => {
      userOptions.value = response.rows;
      userLoading.value = false;
    });
  } else {
    userOptions.value = [];
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  userOptions.value = []; // 清空用户选项
  open.value = true;
  title.value = '添加用户账户';
}

/** 修改按钮操作 */
function handleUpdate(row?: UserAccountVo) {
  reset();
  const id = row?.id || ids.value[0];
  getUserAccount(id).then((response) => {
    Object.assign(form.value, response.data);
    // 如果是修改操作，添加当前用户到选项列表
    if (response.data.userBase) {
      userOptions.value = [
        {
          id: response.data.userId!,
          username: response.data.userBase.username,
          phone: response.data.userBase.phone
        }
      ];
    }
    open.value = true;
    title.value = '修改用户账户';
  });
}

/** 查看按钮操作 */
function handleView(row: UserAccountVo) {
  getUserAccount(row.id!).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  accountRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        updateUserAccount(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addUserAccount(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row?: UserAccountVo) {
  const accountIds = row?.id ? [row.id] : ids.value;
  proxy?.$modal.confirm('是否确认删除用户账户编号为"' + accountIds + '"的数据项？').then(() => {
    delUserAccount(accountIds).then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    });
  });
}

/** 获取性别标签 */
function getGenderLabel(gender?: number) {
  return genderOptions.value.find((item) => item.value === gender)?.label || '未知';
}

/** 获取性别标签类型 */
function getGenderType(gender?: number) {
  switch (gender) {
    case 1:
      return 'primary';
    case 2:
      return 'success';
    default:
      return 'info';
  }
}

/** 获取积分标签类型 */
function getPointsType(points?: number) {
  if (!points) return 'info';
  if (points < 100) return 'warning';
  if (points < 500) return 'success';
  return 'primary';
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.balance {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.balance-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.points-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.points-tip {
  font-size: 12px;
  color: #909399;
}

.time-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;

  .user-detail {
    text-align: left;

    .username {
      font-weight: bold;
      margin-bottom: 4px;
    }

    .phone {
      font-size: 13px;
      color: #909399;
    }
  }
}

.user-info-detail {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 12px;

  .user-detail {
    text-align: left;

    .username {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .phone,
    .email {
      font-size: 14px;
      color: #606266;
      margin-bottom: 4px;
    }
  }
}
:deep(.el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell) {
  text-align: center;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: flex-end;
}

:deep(.el-empty__description) {
  margin-top: 0;
  font-size: 13px;
}
</style>
